﻿using System;
using System.ComponentModel;
using System.Runtime;

namespace Moonlite.Data.Configuration
{
    /// <summary>
    /// Provides a base for type converters.
    /// </summary>
    internal abstract class ConfigurationConverterBase : TypeConverter
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationConverterBase"/> class.
        /// </summary>
        [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
        protected ConfigurationConverterBase()
        {
        }

        /// <summary>
        /// Determines whether this instance can convert from the specified type descriptor context.
        /// </summary>
        /// <param name="ctx">The type descriptor context.</param>
        /// <param name="type">The type.</param>
        /// <returns>
        /// 	<c>true</c> if this instance can convert from the specified type descriptor context; otherwise, <c>false</c>.
        /// </returns>
        public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type)
        {
            return (type == typeof(string));
        }

        /// <summary>
        /// Determines whether this instance can convert to the specified type descriptor context.
        /// </summary>
        /// <param name="ctx">The CTX.</param>
        /// <param name="type">The type.</param>
        /// <returns>
        /// 	<c>true</c> if this instance can convert to the specified type descriptor context; otherwise, <c>false</c>.
        /// </returns>
        public override bool CanConvertTo(ITypeDescriptorContext ctx, Type type)
        {
            return (type == typeof(string));
        }

        /// <summary>
        /// Validates the type.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="expected">The expected.</param>
        internal void ValidateType(object value, Type expected)
        {
            if ((value != null) && (value.GetType() != expected))
            {
                throw new ArgumentException(string.Format("The converter cannot convert values with type '{0}'.", new object[] { expected.Name }));
            }
        }
    }
}
